<?php

namespace App\Repositories;

use App\Events\WechatSubscribe;
use App\Interfaces\DistributeInterface;
use App\Interfaces\UserInterface;
use App\Notifications\UserNotification;
use App\OrderPay;
use App\User;
use App\UserLeader;
use App\UserMoneyLog;
use App\UserTeam;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Intervention\Image\Imagick\Font;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */
class UserRepository implements UserInterface
{
    protected $distribute;


    public function createWechatUserByOpenid($openid)
    {

        $app = \EasyWeChat::officialAccount();

        $userinfo = $app->user->get($openid);

        return $this->createWechatUserByUserInfo($userinfo,1);
    }

    public function createWechatUserByUserInfo($userInfo,$is_subscribe=0)
    {

        $user = User::where('openid', $userInfo['openid'])->first();
        if (!$user) {
            $user = new User();
            $user->openid = $userInfo['openid'];
            $user->name = $userInfo['nickname'];
            $user->headimgurl = $userInfo['headimgurl'];
            $user->sex = $userInfo['sex'];
            $user->city = $userInfo['city'];
            $user->province = $userInfo['province'];
            $user->country = $userInfo['country'];
            $user->subscribe=$is_subscribe;

            $user->save();
            
            if($is_subscribe==1){
                //新关注用户
              //  event(new WechatSubscribe($user));
            }
            //判断url 是否有leaderId 参数
            if (\Request::get('leaderId')) {

                $this->distribute = new DistributeRepository();
                $this->distribute->bindDistribute($user, \Request::get('leaderId'));
            };
        }else{
            //关注字段
           if($user->subscribe==0&&$is_subscribe==1){
               //新关注用户
               \Log::info('新用户注册');
               event(new WechatSubscribe($user));
               $user->subscribe=1;
               $user->subscribe_time=Carbon::now();
               $user->save();
           }
        }
        //执行登陆
        \Auth::loginUsingId($user->id);
        return $user;
    }

    /**
     * @param User $user
     * 会员升级
     */
    public function checkTeamLeavel(User $user)
    {

        //查出下一级的等级
        $level = UserTeam::where('level', '>', $user->team_level_id)->orderBy('level', 'desc')
            ->get();
        if ($level->isNotEmpty()) {
            $is_send=0;
            foreach ($level as $v) {
                if ($user->team_money + $user->distribution_money >= $v->user_money && $user->promotion_number >= $v->user_num && $user->team_level_id < $v->level) {
                    $user->team_level_id = $v->level;
                    $is_send=1;
                }
            }
            $user->save();
            if($is_send==1){
                $this->team_level_notice($user);
            }

        }

    }
    public function team_level_notice(User $user){
        $user->notify(new UserNotification([
            'template_id' => '023vU3zM6H9llyUwGwa8bd8hvhbBXOU2FeR65jogcGo',
            'url' => route('myTeam'),
            'data' => [
                'first' => '亲爱的'.$user->name.'您好!您已成功升级会员级别',
                'keyword1' => '加点幸福',
                'keyword2' => $user->team->name,
                'keyword3' => \Illuminate\Support\Carbon::now(),
                'remark' => '干的漂亮，继续加油',
            ]

        ]));
    }
    public function SendOrderNotice(User $user,OrderPay $orderPay){
        $good=$orderPay->goods;
        $goodsName='';
        foreach ($good as $item){
            $goodsName.=$item->good_object['goods_name'].',';
        }

        $user->notify(new UserNotification([
            'template_id' => '3LVe9ws5glNAAfMjxuk8N-KfyIzt_5FkK-Wsm0bVNlc',
            'url' => route('order.pay',['orderId'=>$orderPay->order_pay_id]),
            'data' => [
                'first' => '商品已在送往客官的路上',
                'keyword1' => rtrim($goodsName,','),
                'keyword2' => '已发货',
                'keyword3' =>$orderPay->express_company,
                'keyword4'=>$orderPay->mail_no ?? '暂无',
                'remark' => \Illuminate\Support\Carbon::now(),

            ]

        ]));
    }
    public function checkTeamLeavelReduce(User $user)
    {
        //查出下一级的等级
        $level = UserTeam::where('level', '<', $user->team_level_id)->orderBy('level', 'desc')
            ->get();
        //用户降级
        if ($level->isNotEmpty() && $user->is_regrade != 1) {

            foreach ($level as $v) {

                if ($user->team_money + $user->distribution_money <= $v->user_money || $user->promotion_number <= $v->user_num) {

                    $user->team_level_id = $v->level;
                }
            }

            $user->save();
        }
        //todo 微信通知会员降级
    }

    /**
     * @param User $user
     * 微信关注二维码
     */
    public function createUserQrcode(User $user)
    {//创建微信关注二维码
        return \Cache::remember('userQrcode' . $user->id, '1', function () use ($user) {
            $app = \EasyWeChat::officialAccount();
            if ($user->id > 100000) {
                //生成临时二维码
                $result = $app->qrcode->forever($user->id);
                $url = $app->qrcode->url($result['ticket']);
            } else {
                $url = \Cache::remember('qrcode' . $user->id, '30', function () use ($user, $app) {
                    $result = $app->qrcode->temporary($user->id, 30 * 24 * 3600);
                    return $url = $app->qrcode->url($result['ticket']);
                });

            }
            try {
                $client = new Client();
                $data = $client->request('get', $url)->getBody()->getContents();
                $filename = 'qrcode/qrcode' . $user->id . '.png';
                \Storage::put($filename, $data);
                $disk = config('filesystems.disks');
                $driver = config('filesystems.default');

                return $url = $disk[$driver]['url'].'/'.$filename;

            } catch (RequestException $e) {
                echo 'fetch fail';
            }
        });

    }

    /**
     * 个人分享二维码
     */
    public function userQrcode(User $user,$repeate=false)
    {
        $userId = hashid_encode($user->id);
        $path= 'qrcode/qqqrcode' . $user->id . '.png';
        if(!file_exists($path)||$repeate==true) {
            is_dir('qrcode') ? '' : mkdir('qrcode',0777);
            $qrcode = QrCode::size(500)->format('png')->generate(route('user.qrcode', ['hashid' => $userId]));
            $client = new Client();
            $data = $client->request('get', $user->headimgurl)->getBody()->getContents();
            $qrcode = \Image::make($qrcode)->resize(300, 300);
            $image = \Intervention\Image\Facades\Image::make('FENXIAO/images/friend.jpg')->insert($qrcode, 'top-left', 210, 400)->insert($data,'',10,10)->text(str_limit($user->name, 16),150,50,function ($font){
                $font->file('font/gb.ttc');
                $font->size(28);
                $font->align('left');
                $font->valign('top');
                $font->angle(0);

            });
            $file=$image->save($path);
        }
        return $path;
    }

    /**
     * @param User $user
     * @return int
     * 1级二级朋友
     */
    public function getMyFriendNumber(User $user)
    {

        return $user->promotion_number + $this->getMyFriendSecondNumber($user);
    }

    /**
     * @param User $user
     * 二级朋友数量
     */
    public function getMyFriendSecondNumber(User $user)
    {
        return User::whereRaw("find_in_set($user->id,team_path) = 3")->count();
    }

    /**
     * 注册成功通知
     * @param User $user
     * @param string $leader
     */
    public function registerNotice(User $user, $leader = '')
    {
        Auth::user()->notify(new \App\Notifications\UserNotification  (['template_id' => 'Kh66YgtBBP6nzWvADwnVMEP16QgF8xEmE94ar92wLqU', 'url' => 'http://laravel.natapp1.cc/', 'data' => [
            'first' => '你成为哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈',
            'keyword1' => '1',
            'keyword2' => '2',
            'keyword3' => '3',
            'keyword4' => '4',
            'keyword5' => '5',
            'remark' => '[点击购买]',

        ]]));
    }
    public function getMyTeamCount(User $user){
     return
         $totalNum = User::whereRaw("find_in_set($user->id,team_path) >0")->groupBy('team_level_id')->select(\DB::raw('count(id) as count'),'team_level_id')->get()->pluck('count','team_level_id')->toArray();//总数量
    }
    /**
     * @param User $user
     * @return int
     * 团队总人数
     */
    public function getMyTeamNumber(User $user)
    {
        $totalNum = User::whereRaw("find_in_set($user->id,team_path) >0")->count();//总数量
        //筛选掉比自己等级高的人
        $teamList = User::whereRaw("find_in_set($user->id,team_path) >0")->where('team_level_id', '>', $user->team_level_id)->get();
        $num = 0;
        if ($teamList->isNotEmpty()) {
            $total = User::query();
            foreach ($teamList as $k => $v) {
                if ($k == 0) {
                    $total = $total->whereRaw("find_in_set($v->id,team_path) >0");
                } else {
                    $total = $total->orWhereRaw("find_in_set($v->id,team_path) >0");
                }
            }
            $num = $total->count();
        }
        return $totalNum - $num;
    }

    //结算收益
    public function setellement($ids)
    {
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        \DB::transaction(function () use ($ids) {
            foreach ($ids as $v) {
                $userMoneyLog = UserMoneyLog::find($v);
                if ($userMoneyLog->status!=1) {
                    $userMoneyLog->status = 1;
                    $userMoneyLog->save();
                    User::where('id', $userMoneyLog->leader_id)->increment('money', $userMoneyLog->price);
                    \Log::info($userMoneyLog->leader_id,[$userMoneyLog->price]);
                    if ($userMoneyLog->type == 0) {
                        User::where('id', $userMoneyLog->leader_id)->increment('distribution_used_money', $userMoneyLog->price);
                    } else {
                        User::where('id', $userMoneyLog->leader_id)->increment('team_used_money', $userMoneyLog->price);
                    }
                }
            }
        });
    }

    //预绑定分销关系
    public function toBind(User $user, $leaderId)
    {
        //查询用户是否有领导
        if (!$user->leader && $user->leader != $leaderId && $user->id !=$leaderId) {
            $userLeader = UserLeader::where('user_id', $user->id)->first();
            if (!$userLeader) {
                $userLeader = new UserLeader();
                $userLeader->user_id = $user->id;
            }
            $userLeader->leader_id = $leaderId;
            $userLeader->save();
        }


    }

}